package com.woniu.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.exception.order.OrderException;
import com.woniu.exception.order.OrderExceptionCode;
import com.woniu.model.Result;
import com.woniu.order.client.EmployeeClient;
import com.woniu.order.client.FlowClient;
import com.woniu.order.cliententity.entity.Employee;
import com.woniu.order.cliententity.entity.FlowHandle;
import com.woniu.order.cliententity.form.AddHandelForm;
import com.woniu.order.mapper.TVisitMapper;
import com.woniu.order.model.TVisit;
import com.woniu.order.param.AddVisitParam;
import com.woniu.order.service.TVisitService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年06月05日
 */
@Service
public class TVisitServiceImpl extends ServiceImpl<TVisitMapper, TVisit> implements TVisitService {

    @Resource
    private TVisitMapper visitMapper;
    @Resource
    private EmployeeClient employeeClient;

    @Resource
    private FlowClient flowClient;

    /**
     * 站长回访
     * @param userId 当前登录站长id
     * @param toBean 表单id 回访记录信息
     * @return 生成记录
     */
    @Override
    public TVisit userVisit(Integer userId, AddVisitParam toBean) {
        //获取站长信息
        Result<Employee> employeeResult = employeeClient.byId(userId);
        if (employeeResult.getCode()!=200){
            throw new OrderException(employeeResult.getCode(), employeeResult.getMessage());
        }
        QueryWrapper<TVisit> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",toBean.getOrderNum());
        TVisit tVisit = visitMapper.selectOne(wrapper);
        if (tVisit==null){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_VISIT);
        }
        //判断是该回访的站长
        if (employeeResult.getData().getStationId()!=tVisit.getStationId().longValue()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_VISIT);
        }
        tVisit.setVisitRecording(toBean.getVisitRecording());
        tVisit.setVisitTime(LocalDateTime.now());
        visitMapper.insert(tVisit);
        //client 流程下一步 9已完成
        AddHandelForm addHandelForm = new AddHandelForm(null, 9, userId, tVisit.getOrderNum(), null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        return tVisit;
    }
}
